package com.kyub.dynamoscaffold

import org.codehaus.groovy.grails.scaffolding.*
import org.codehaus.groovy.grails.commons.GrailsDomainClass
import org.springframework.core.io.ClassPathResource
import org.springframework.core.io.FileSystemResource
import grails.util.BuildSettingsHolder
import org.codehaus.groovy.grails.commons.ApplicationHolder
import org.apache.commons.logging.LogFactory
import org.apache.commons.logging.Log
import org.codehaus.groovy.grails.commons.ConfigurationHolder;

public class DynaTemplateGenerator extends  DefaultGrailsTemplateGenerator {

  def dynaControllerRowActionsMap

  def dynaControllerListItemsMap

  def dynaControllerInlinesMap

  def dynaControllerShowItemsMap

  def dynaControllerSearchItemsMap

  static final Log LOG = LogFactory.getLog(DefaultGrailsTemplateGenerator.class);

  def DynaTemplateGenerator(classLoader) {
    super(classLoader);
  }

  def void generateView(GrailsDomainClass domainClass, String viewName, Writer out) {

    LOG.error(dynaControllerListItemsMap[domainClass.logicalPropertyName]) 



    def templateText = getTemplateText("${viewName}.gsp")

        def t = engine.createTemplate(templateText)
        def multiPart = domainClass.properties.find {it.type == ([] as Byte[]).class || it.type == ([] as byte[]).class}

        def packageName = domainClass.packageName ? "<%@ page import=\"${domainClass.fullName}\" %>" : ""
        def binding = [packageName: packageName,
                domainClass: domainClass,
                multiPart: multiPart,
                className: domainClass.shortName,
                propertyName:  getPropertyName(domainClass),
                renderEditor: renderEditor,
                comparator: org.codehaus.groovy.grails.scaffolding.DomainClassPropertyComparator.class  ,
                wcomparator: com.kyub.dynamoscaffold.ListDomPropertyComparator.class ,
                rowActions: dynaControllerRowActionsMap[domainClass.logicalPropertyName],
                listItems: dynaControllerListItemsMap[domainClass.logicalPropertyName],
                inlines: dynaControllerInlinesMap[domainClass.logicalPropertyName],
                showItems:dynaControllerShowItemsMap[domainClass.logicalPropertyName],
                searchItems:dynaControllerSearchItemsMap[domainClass.logicalPropertyName]]





        try{
          def StringWriter w = new StringWriter();
          LOG.error(t.make(binding).writeTo(w))

          t.make(binding).writeTo(out)
          } catch(Exception e){
               e.printStackTrace()

        }


  }

  void generateController(GrailsDomainClass domainClass, Writer out) {
         def templateText = getTemplateText("Controller.groovy")

         def binding = [packageName: domainClass.packageName,
                 domainClass: domainClass,
                 className: domainClass.shortName,
                 propertyName: getPropertyName(domainClass),
                 comparator: org.codehaus.groovy.grails.scaffolding.DomainClassPropertyComparator.class,
                 inlines: dynaControllerInlinesMap[domainClass.logicalPropertyName]]

         def t = engine.createTemplate(templateText)

          def StringWriter w = new StringWriter();
          LOG.error(t.make(binding).writeTo(w))

         t.make(binding).writeTo(out)
     }


  private getTemplateText(String template) {
        /*def application = ApplicationHolder.getApplication()
        // first check for presence of template in application
        if (resourceLoader && application?.warDeployed) {
            return resourceLoader.getResource("/WEB-INF/templates/scaffolding/${template}").inputStream.text
        }
        else {
            def templateFile = new FileSystemResource("${basedir}/src/templates/scaffolding/${template}")
            if (!templateFile.exists()) {
                // template not found in application, use default template
                def grailsHome = BuildSettingsHolder.settings?.grailsHome

                if (grailsHome) {
                    templateFile = new FileSystemResource("${grailsHome}/src/grails/templates/scaffolding/${template}")
                }
                else {
                    templateFile = new ClassPathResource("src/grails/templates/scaffolding/${template}")
                }
            }
            return templateFile.inputStream.getText()
        }*/
        def templateFile
        def skin = ConfigurationHolder.config?.dynamoscaffoldSkin
       if(skin){
         templateFile = new FileSystemResource("${basedir}/src/dynamoscaffold/${skin}/${template}")
       }else{
         templateFile = new FileSystemResource("${basedir}/src/dynamoscaffold/default/${template}")
       }
       return templateFile.inputStream.getText()

    }

  private def getPropertyName(GrailsDomainClass domainClass) {
        return domainClass.propertyName + 'Instance'
    }


}